Central Article

Migrating Your Flash Applications to Macromedia Central

Geoffrey Williams

gsolo.com/blog

There are many reasons why you should consider migrating your existing Rich Internet Applications to Macromedia Central. Take advantage of the built-in try/buy framework of Central, its awareness of occasionally connected clients, its integration with other installed Central applications, and a familiar IDE—just to name a few. The ubiquity of Flash Player allows for easy installations from almost anywhere and Central provides a browser-independent environment that can be distributed regardless of the users' operating system.

For those of you who are new to Central, I recommend reading up on it first. The Macromedia Central Developer Center contains many resources to get you started with Macromedia Flash and Central. Many of them are also covered in the Macromedia Central SDK. This article is geared towards Flash developers who have varied levels of experience. Read onward to learn some helpful hints and tips on migrating your existing Flash applications to Macromedia Central.

Note: When you migrate your existing Flash applications there are a few extra steps you must follow in order prepare them for Central. In addition to initializing the application within the Central environment, there are limited export and debugging options.

New Features in Macromedia Central

Let's take a look at what new functionality is built into the specialized version of Flash Player for Central. Flash Player in Central is actually based on Flash Player 6, not Flash Player 7. This specialized player includes some Flash Player 7 optimizations along with some new features that I describe below.

Support for Additional Image Formats

As you may know, Flash inherited the ability to dynamically load JPEGs starting with Flash Player 6. This was a big step in the evolution of Flash Player. To this day, however, Flash does not support the loading of other image file formats due to limitations imposed on the player's file size. Because of fewer restrictions on its size, Macromedia Central has built-in support for GIFs. Transparent GIF files are supported too; however, animated GIFs are not. In addition, Central can load progressive JPEGs. This new functionality helps support web services that may provide these proprietary image formats for use with standard web browsers.

Operating System Level Tooltips

Macromedia Central taps into the operating system to support OS-level tooltips. The implementation API couldn't be any simpler:

icon_mc.tooltipText = "This is a Tooltip";

When a user rolls over the icon, after a slight delay a tooltip appears. Central determines when the tooltips should be displayed and removed; no additional code is needed

Clearing the tooltip (removing the tooltip functionality from the movie clip) is just as easy:

icon_mc.tooltipText = "";

For those who aren't quite familiar with tooltips or their function, tooltips are used essentially to add a verbose description to text, buttons, icons, or other images—especially when icons appear without descriptive text underneath. Similar to the alt attribute in HTML, tooltips are a usability utility that help make applications accessible.

Consuming Web Services

Web services allow applications to cite data from other sources, regardless of how that data is stored or what platform the services are located on. Macromedia Central's built-in support for web services makes communication with these remote services a breeze using standard SOAP and XML-RPC protocols. If you're familiar with the Web Services API within Flash MX 2004, the implementation is quite the same:

myWebService = new WebService("http://www.myCompany.com/myService.wsdl");
callback1 = myWebService.getWeather("02451"); 
callback1.onResult = function(result)
{
     trace(resut);
}     

The XML-RPC (Remote Procedure Call) is just as easy:

myRPCFactory = new RPCFactory(http://www.myCompany.com/myRPC.xml) ;
callback1 = myRPCFactory.createCall("methodName", Arg1, Arg2) ;
callback1.onResult = function(result) 
{ 
     trace(result);
}

Implementation of Regular Expressions

Based on the ECMAScript standard, Macromedia Central supports an API for regular expression evaluation (pattern matching):

html_str = "This is an HTML <b>string</b>";
bold_re = new RegExp("<b>(.*?)</b>"); 
result = bold_re.match(html_str); // result[0] == "string"

Macromedia uses Perl Compatible Regular Expressions, or PCRE (www.pcre.org), for its regular expression library, which uses Perl's regular expression syntax. Read more about it:

The following are examples of implementation of these methods:

Things to Avoid and Watch Out For

When you develop your application there are a few things you need to watch out for. Some things just work differently within Central because of how the movie clip architecture is set up. Simple things like persistent global variables and intervals can slow down the performance of not only your application but other Central applications as well. It's up to the developer to make sure things run smoothly.

Avoid: _root

You've probably heard about this one for a while: Avoid references to _root. In fact, you may have a hard time migrating an existing application that relies heavily on the use of _root. Here's why: Because your application is loaded into a container clip, any references to _root are actuality referencing the top-level SWF, which is no longer your main application timeline. Here are a few suggestions for overcoming this variance in scope.

Create a global reference to the application's root. Then set up existing calls to root so they reference appRoot instead of _root:

_global.appRoot = this;

A more appropriate way of doing this might be to create a controller, which is a variable reference to the root of the application:

// appRoot._mc.sub_mc
appRoot._mc.sub_mc.appRoot = this;

Another option, provided by Fernando Flórez of Funciton, attempts to give you the _lockroot functionality of Flash Player 7. Although it looks like it could be a bit bulky, it seems to help automate things:

www.onelx.com/blog/en/archives/000166.php

There's always the option of hard-coding it all.

Adjusting your existing application to accompany this workaround could end up being a laborious task. With Flash MX 2004 however, the global Find and Replace comes in quite handy.

Watch Out: _global and prototypes

Although you can use _global, there are a few things you need to watch out for. Remember that the application shell, Console (notices/pods), and agent are run in separate instances of the Central Flash Player. You have to clean them up when switching between applications. Globals and prototypes persist within the application shell when switching between applications that come from the same domain. So when you use _global and prototypes within the agent and Console you may get conflicting namespaces, whether the user has two instances of your application's pod open or you have two application agents running from the same domain.

Best practices would create a unique namespace for each instance of a global variable or prototype:

_global.fooApplication = new Object();
_global.fooApplication.bar = "foobar';
// ...
function onDeactivate()
{
     delete _global.fooApplication;
}

Application developers are encouraged to avoid using the global scope.

Watch Out: setInterval

Remember that your application will not always be the only one running within Central. It's up to the developer to clean up any loose ends that may be hanging around if your application is uninstalled or deactivated. Intervals persist similarly to _global and prototypes. When someone switches from your application while an interval is running in the background, it continues to run; returning to your application may cause multiple instances of your interval to occur, producing undesirable results. Therefore, clear your intervals when your application is deactivated.

Example 1:

myInterval = setInterval(updateData, 300000);
// ...
function onDeactivate()
{
     clearInterval(myInterval);
}

Example 2:

function onDeactivate()
{
     for (var i = setInterval(Function, 1000); i >= 0; i--) 
{
     clearInterval(i);
}
}

Another way to help facilitate the management of your application's intervals is to create an interval manager by developing an object with methods that manage the setting and clearing of your intervals.

In addition, one preventative step when using intervals is to call clearInterval before your setInterval statement. Although it creates some overhead, it assures that you are not starting up multiple identical intervals (where clearInterval would not necessarily clear all intervals).

Watch Out: _mc.loadMovie

If you load a SWF, GIF, or JPEG from another domain into a movie clip, the movie clip is considered to be from another domain. This means your movie can no longer call methods on it unless the movie clip incorporates allowDomain() for your domain, which isn't possible with the two supported image formats. Using the global loadMovie(mc,...) or unloadMovie(mc,...) works, however.

Testing and Debugging Your Application

Using trace to debug doesn't get you very far when developing Central applications. Presumably when you use any of Central's functionality your application won't behave as intended within the standard Flash Player or IDE. Instead, it's recommended that you use a method of testing that incorporates a debugging application (client) while your application serves data to the client over LocalConnection. Thankfully Macromedia put together an application and API that helps with this testing process (see Tracer in the Application Finder). In addition, Macromedia included a Debug panel with the SDK that allows the implementation of the trace function. You can find the MXP installer and source code in the SDK\Utilities\DebugPanel folder. After you install it, you can simply send information to the Debug panel by using the trace function:

trace("Hello, this is from Central");

The information is then displayed within the Debug panel. Built-in support for tracing and formatting data types such as arrays and XML will also be available. The Debug panel uses the same LocalConnection client/server method I mentioned just above.

Enabling debugging of your application is a simple process:

debug.enabled = true;

This allows Central-level annotations to be posted to the Debug panel. An example might include the amount of time it takes to parse a WSDL document. The standard debugger built into the Flash IDE will not be operational, however.

Initiating Your Application

You have your application all set up and you're just waiting to get it into Central. The first couple of steps include initiating your application so that Central knows it's indeed a Central application.

Central.initApplication

Although it will more than likely be your last line of code, the first step in initiating your application is calling the initApplication method. The Central.initApplication method tells the Central shell that your movie has loaded. This method accepts two parameters: the application object and the event handler object. The application object references the "root" timeline of your application while the event handler object is the location of your application-specific event handlers (more information on those just ahead). You'll more than likely put your initiation code on the root timeline, in which case the following example is all you need to get things started:

Central.initApplication(this, this);

Simple, right? One issue may arise when you use screens or forms in Flash MX Professional 2004. For example, if you place your code on the topmost screen, the root of your application is now the parent movie clip, "root," which holds your screen and form components. In this case, a simple modification to the code tells Central how everything is set up:

Central.initApplication(_parent, this);

Application.onActivate

The Central shell calls this function when the application is about to be displayed in the application window. Within the onActivate() function you define your initial variables, make connections to remote data, and handle any application initialization. Without this step, most of the additional functionalities of Central are lost.

When Central calls onActivate() it passes five parameters to it. The first one is the Shell object reference which allows you to make calls to the Central shell methods.

In the following example, onActivate() assigns the shell callback object to the variable gShell and then calls the shell's setStatus() function:

function onActivate(shellRef, appID, shellID, baseTabIndex, initialData)
{
     gShell = shellRef;
     gShell.setStatus("The onActivate call has been received");
}

appID

The appID parameter provides a unique ID number for the current instance of your application. By incorporating this ID into the name of a local shared object, you can use it to create local shared objects that are specific to the application instance. In these local shared objects you can store information such as the display state. You can use the same technique to create uniquely named local connection objects for communicating with pods or agents associated with your application.

shellD

The shellID parameter provides a unique ID number for the shell (application window) that the application runs in. By combining the shellID parameter with the appID parameter in a variable name, you can allow multiple instances of the same application to create per-instance local connections. Use these local connections to communicate among applications, pods, and agents. An application should not use the shellID parameter to create persistent local shared objects because the value changes across sessions.

baseTabIndex

The baseTabIndex parameter provides seamless tab-navigation support. Set the tabbing order indexes on your application controls to start at this base index so there won't be any conflict with surrounding application window controls.

initialData

You can use the initialData parameter to pass application-specific data to an application from a pod. This can be useful when a pod calls Console.loadApplication() to display the application in the shell. For example, the application might initially display data contained in the appData parameter. The appData parameter can be a string or object reference.

The following onActivate() function is from the StockWatcher application's stock.as file. It assigns the shell callback object to the variable gShell, assigns the application ID to the variable gAppID, and creates a unique string identifying the application by concatenating the value of gAppName and shellID:

function onActivate(shellRef, appID, shellID, baseTabIndex, initialData) 
{
     gShell = shell;
     gAppID = id;
     gAppName += shellID;
     textField.tabIndex = baseTabIndex + 1;
     dataGrid.tabIndex = baseTabIndex + 2;
     // additional initialization
}

Application.onResize

In addition to creating your shell references, setting up the tab order, and so on within the onActivate() function, this is where you would make any connections to local shared objects and initiate any LocalConnections to your application's agent. It is also recommended that you call the onResize event handler at this point to make sure your application appears correctly within the application shell.

The onResize() function is called by the Central shell when the application window is resized. In this function, your application should call shellRef.getBounds() to determine the new window size and adjust its own size to fill the window accordingly. The getBounds() method returns an object with two properties: height and width.

Application.getMinimumSize, Application.getMaximumSize

Each time your application is displayed in the application window, the Central shell calls getMinimumSize() and getMaximumSize() to determine the minimum and maximum dimensions for your application. Each function should return an object containing two properties representing the minimum and maximum width and height of your application. If a user switches to your application while the application window is smaller than your specified minimum size, the Central application window expands accordingly. Similarly, if the user switches to the application while the application window is larger than the application's maximum size, Central resizes the application window to the specified size:

function getMinimumSize() 
{
     return {width:400, height:400};
}

function getMaximumSize() 
{
     return {width:800, height:600};
}

Each of these functions is optional. If your application does not include either one, the application window will not automatically resize itself when Central makes the call.

Application.showPrefercnces

The showPreferences() function is called by the Central shell when the user chooses Preferences from the ApplicationName menu item. In this function, you are encouraged to use ActionScript calls that display a Preferences screen for your application. The preferences option for an application only appears if the following attribute is in the application tag of the Product XML Descriptor File:

hasPreferences="true"

Otherwise, it does not appear. Local shared objects are a good way to store application-specific preferences data that must persist between application sessions.

Cleaning Up Your Application

When someone switches from your application or if your application is uninstalled, it is best to clean up any processes running as well as any files left or anything else not cleaned up by the uninstallation process.

Application.onDeactivate

The Central shell calls the onDeactivate() function when the application is about to be shut down. This can happen when the user selects another application to be displayed in the application window, the application window is closed, or the user quits Central. You should assume that your application is going to be shut down after this method is called. The onDeactivate() function is a good place to save data, remove setInterval statements, close data connections, and clear global variables. Be aware that you cannot use local connection methods in the onDeactivate() function.

Within this function, you should implement some sort of functionality that remembers users' last state when they used your application. This conveys the feeling of "tabbed browsing," which allows users to switch to another application and then switch back to yours and continue right where they left off. Consider, for example, a text editor that automatically saves any text in a field when a user switches to a news application. The user copies a line of text from the news application, switches back to the text editor, and pastes the text into what they're working on.

Application.onUninstall

The Central shell calls the onUninstall() function when the application is being uninstalled. This occurs when the user selects View > My Applications and then uninstalls the application in the My Applications screen. Be sure to Uinclude code in this function that cleans up any local shared objects created by your application by setting them to zero. Central does not do this for you. However, Central does delete files cached with the addToLocalInternetCache() command when the application caching them is uninstalled.

Enhancing Your Application

Believe it or not, that's just about all there is to migrating your existing applications to Macromedia Central, aside from the publishing process that I cover briefly at the end. The fun has only begun. Part of migrating your application to Macromedia Central requires taking advantage of all the added functionality built into the Central framework. This includes developing your application for online and offline use; standardizing your application's user interface to conform to the consistent look and feel throughout the Central environment; managing your application data with agents; and incorporating pods and notices, to name a few. Macromedia Central is a powerful medium to enhance and distribute your applications. The following section will give you an overview of the implementation of these new features into your application.

Developing for Online and Offline Use

One of the many advantages of using Central rather than a web browser or other medium is the ability to develop more intuitively for an occasionally connected platform. Macromedia Central caters to mobile users, allowing you to cache files and data for use when they're offline. Migrating your existing applications and incorporating this functionality gives end users an overall better user experience.

It is important to understand that users communicate their connection status to Central; Central cannot determine connection status directly. By selecting the lightning bolt in the Central toolbar users can toggle between online and offline mode.

Application.onNetworkChange

The Central shell calls the onNetworkChange(connected) function when the user changes the network connection status (from online to offline and back). Include any code that you want to execute in response to the status change in this function, such as toggling variables used to determine whether to use data from the Internet or from the cache:

function onNetworkChange(connected) 
{
     gOnline = connected;
     if (gOnline)
     {
          updateData();
     }
}

Shell.isConnected

In addition to the application (console/agent) function onNetworkChange, the isConnected function allows you to determine Central's connection status. The isConnected function returns a Boolean value representing the users' connection status: true if a connection is present and false if no connection is available.

Caching Data for Offline Use

As I wrote earlier, your ability to cache data for offline use is a large benefit of developing applications for Macromedia Central. This enables users of occasionally connected devices (laptops and PDAs) to access your application's data and functionality where live data is not available. For already parsed data, user preferences, and so forth, it's best to use the familiar shared objects. For other sources of data, there is an XML node you can add to your installation file, as well as a simple API that is implemented for this caching process.

The first method of caching files is through your Product XML Descriptor File (more about that at the end). Simply adding the following line caches the file when your application is installed:

<file src="http://www.myCompany.com/images/shared/product_logos/logo.jpg"/>

The second method is a built-in API:

gShell.addToLocalInternetCache("http://www.myCompany.com/logos/logo_1.jpg");

The first parameter is the URL of the file you want to cache. Two optional parameters include a Boolean value indicating whether to overwrite the file if it already exists in the cache. The next parameter is either a Date object or a number, specifying the date or how many days until the file expires in the cache.

Other methods include gShell.inLocalInternetCache(url), which returns a Boolean value reflecting the status of the file, representing whether or not it is in the user's local Internet cache; and removeFromLocalInternetCache(url), which removes the file from the user's local hard drive.

The default amount of space shared by all applications running in Central is 20 MB. When the application exceeds that amount, it asks the user to allow more space for local Internet files. If the user refuses, the file is not cached.

Incorporating the Macromedia Central Components

Why use Macromedia Central components? There are a couple of reasons. It is important to provide users with a common user interface when developing applications. A common user interface means a small learning curve because users are already familiar with how similar elements work in other applications.

Your application can take advantage of a myriad of components installed with Central without any additional overhead. Unique components built specifically for Central include AccordianTab, ExpandingPod, DialogBox, IconMenu, RoundIconButton, TextInputField, and four image-only components. Other components include: Calendar, CheckBox, ComboBox, DataGrid, IconButtom, ListBox, ProgressBar, PushButtom, RadioButtom, ScrollBar, and ScrollPane. Unlike Flash UI components, these cannot be skinned and the use of styles is not supported. Some components, however, contain additional functionalities and are customizable to some degree.

Macromedia strongly recommends using the components' default font settings, which are 10-point Verdana, text color #2B333C, and disabled text color #AAB3B3. However, you may customize text font and size. Some components, such as AccordianTab and DataGrid, include functionality for color changes to match the color of your application; other customizable areas include component dimensions.

Managing Your Data

Macromedia Central provides a framework to help simplify the management of data between your applications' elements. This functionality is provided in the form of agents and using the LCService and LCDataProvider APIs. Additional documentation about these implementations appears in the Macromedia Central SDK.

Agents

One optional component for your application is an agent. Agents provide an environment for your application, or multiple instances of your application, to communicate to a single data manager. An agent is a "headless SWF" (a SWF without any graphical elements) that processes tasks in the background, invisible to the user. Even when your application is not running, an agent can poll for data, monitor the connection, and so on. When developing your agent, keep in mind that users can disable them. Your product should work whether users disable agents or not.

LCService

To enhance the communication between your application elements, Central provides LCService as a more robust solution than the standard LocalConnection object. The enhanced server/client method calling is ideal for applications that have multiple parts. It allows the application, agent, and pods to communicate among one another more easily by facilitating the ability to define functions that be called from other application parts (for example, a pod calling a function in an agent). A typical implementation puts the server type functionality into your agent, while the corresponding clients are put into the application and pods. Below is a brief example:

// Interface.as
ITestInterface = new Object();
ITestInterface.name = "ITestInterface";
ITestInterface.interfaces = new Array();
ITestInterface.interfaces["Client"] = [];
ITestInterface.interfaces["Server"] = ["echo"];


// ServerAgent.as
#include "Interface.as"
function onActivate( agentManager, agentId, initialData ) 
     { 
          gAgentManager = agentManager;
          gTestService = Central.LCService.createServer( ITestInterface, this ); 
     }
function echo( echoString ) 
     {
          return echoString; 
     }


// ClientApp.as 
#include "Interface.as"
function onActivate( shell, appId, shellId, baseTabIndex, initialData ) 
     { 
          gShell = shell;
          gShellUID = String(appId) + "_" + String(shellId);
          gTestService = Central.LCService.createClient( ITestInterface, gShellUID, this );
          gTestService.echo("foobar"); 
     }
function echo_Result( echoString ) 
     {
          trace("echo_Result = " + echoString );
     }
Central.initApplication( this, this ); 

LCDataProvider

Similar to LCService, LCDataProvider provides a central location to store, manage, and access data. Based on the DataProvider object, LCDataProvider allows you to create a central location for the application and pods to access data. Creating the client and server halves of LCDataProvider is similar to using the LCService object, only you don't have to specify any methods:

// create the LCDataProvider Server
foodList_dp = Central.LCDataProvider.createServer("food_list"); 

// create an array
     var foods = ["corn", "chicken"];

// populate the LCDataProvider object
     foodList_dp.setData( foods );

     // ------

     // create the LCDataProvider Client
     foodList_dp = Central.LCDataProvider.createClient( this.fClientID, "food_list" ); 
     myComboBox.setDataProvider( foodList_dp );

Incorporating Pods and Notices into Your Application

Pods are small iterations of your application and notices advise users of important events. Use these enhancements to provide additional methods of interaction and feedback for users.

Pods

Pods are small extensions of an application that are housed in the Console. They are useful for displaying frequently updated data that users might want to view on the desktop without having to open the application window. Pods can also be designed as scaled-down versions of the host application. An example might be a chat application that handles private or one-on-one conversations through a pod, while the application itself hosts the chat room, user list, room list, and so on. Pods are created during installation according to the product.xml file or dynamically through the API. Pods can be spawned at installation time or can come into view dynamically through the API or user interface.

Notices

An application, pod, or agent running the background can generate notices, which are used to notify users of important events pertaining to a specific application:

notice = new Object();
notice.name = "Application Notice Event";
notice.description = "Click Launch, to open or switch to Application"; 
notice.engageString = "Launch";
notice.navigate = true; 
notice.alert = true;
gManager.addNotice(notice); 

Interaction with notices allows users to launch or switch to the corresponding application.

Deploying Your Application

Publishing and deploying your application involves getting a product ID from Macromedia and setting up your Product XML Descriptor File (product.xml). Register your product with Macromedia and obtain a unique product ID at the following URL:

www.macromedia.com/go/central_productid

On this page you provide the name of your application, along with a brief description, and select a license type. You will automatically be given a product ID for your application.

The product.xml file contains all the information about your application: where your files are located, product description, product versioning, author, and so on. This file installs your application in the Central environment. Here is a sample product.xml file:

<product name="Sample"
created="12/21/2002"
version="1"
lifetime=""
price="Free"
requireVersion="1"
help="productHelp.html"
category="Productivity"
vendor="MyCentralApps"
productID="xxxxxx-xxxxxx-xxxxxx-xxxxxx">
       <author name="MyCentralApps" info="http://www.mycentralapps.com/"/>
       <description>Sample application for Macromedia Central</description>
       <icon src="icons/sample_40.swf" size="40"/>
       <application name="Sample"
             src="sample.swf"
             width="550" height="400"
             help="appHelp.html"
             enabled="true"
             lang="en"
             background="#FFFFFF"
             version="1">
             <icon src="icons/sample_24.jpg" size="24"/>
             <pod name="Sample Tile"
             src="tile.swf"
             height="200"
             editable="true"/>
       </application>
</product>


See the Macromedia Central SDK for additional information about product.xml and publishing your application.

I hope this article gets you started in the right direction at migrating your applications to Macromedia Central. See the Macromedia Central SDK for full documentation, including detailed APIs and information about selling and requesting individual payments within your application. We'll all be looking forward to what comes out of it from developers. Have fun!


About the author

Geoffrey Williams is a Macromedia aficionado and Team Macromedia Volunteer for Central. He has worked with Macromedia products for the better part of five years. Within that time he has learned and mastered Flash, Dreamweaver, and ColdFusion, and has acquired experience with Contribute, HomeSite (CFStudio), Flash Communication Server, Flash Remoting, Fireworks, and FreeHand (not to mention Adobe Illustrator and Photoshop). Geoffrey has extensive experience with ActionScript and Flash development practices, which you can see on FlashKit.com. The majority of his web-based projects involve ColdFusion MX. He has developed a few intranet applications for a nonprofit community association. Current projects include a Rich Internet Application that makes use of the Macromedia Central framework, Flash, and Amazon.com web services. In addition to his technical skills, Geoffrey has over six years of customer service, management, sales, marketing, and print production experience.